package com.pxmeta.app.controller.chat;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.pxmeta.app.controller.chat.dto.BatchLiveDTO;
import com.pxmeta.app.controller.chat.vo.*;
import com.pxmeta.chat.entity.ChatTop;
import com.pxmeta.chat.enums.MsgTypeEnum;
import com.pxmeta.chat.service.HuanxinService;
import com.pxmeta.chat.service.IChatTopService;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.common.utils.agora.AgoraClient;
import com.pxmeta.party.entity.PartyUser;
import com.pxmeta.party.entity.enums.UserLiveStatusEnum;
import com.pxmeta.party.entity.vo.ChannelUserVO;
import com.pxmeta.party.service.IPartyService;
import com.pxmeta.party.service.IPartyUserService;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/chat")
@Api(tags = "聊天",value = "聊天")
@RequiredArgsConstructor
public class ChatController {

    private final HuanxinService huanxinService;
    private final IChatTopService chatTopService;
    private final AgoraClient agoraClient;
    private final IPartyUserService partyUserService;

    private final IUserService userService;


    @GetMapping("/setTopChat")
    @ApiOperation("设置置顶聊天")
    public AjaxResult setTopChat(@RequestParam String chatId){
        Long userId = SecurityUtils.getUserId();
        ChatTop chatTop = new ChatTop();
        chatTop.setChatId(chatId);
        chatTop.setUserId(userId);
        chatTopService.save(chatTop);
        return AjaxResult.success();
    }

    @DeleteMapping("/delTopChat")
    @ApiOperation("取消置顶聊天")
    public AjaxResult delTopChat(@RequestParam String chatId){
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<ChatTop> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ChatTop::getUserId, userId)
                .eq(ChatTop::getChatId, chatId);
        chatTopService.remove(wrapper);
        return AjaxResult.success();
    }


    @GetMapping("/getTopChat")
    @ApiOperation("获取用户置顶聊天列表")
    public AjaxResult<List<String>> getTopChat(){
        LambdaQueryWrapper<ChatTop> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ChatTop::getUserId,SecurityUtils.getUserId());
        List<String> chatIds = chatTopService.list(wrapper).stream().map(ChatTop::getChatId).collect(Collectors.toList());
        return AjaxResult.success(chatIds);
    }

    @SaCheckLogin
    @PutMapping("/setDisturb")
    @ApiOperation("设置免打扰")
    public AjaxResult setDisturb(@RequestParam(defaultValue = "0") String start,
                                 @RequestParam(defaultValue = "0") String end,
                                 @RequestParam String targetId){
        huanxinService.setDisturb(targetId, start, end);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @PutMapping("/cancelDisturb")
    @ApiOperation("取消免打扰")
    public AjaxResult cancelDisturb(){
        String username = SecurityUtils.getUsername();
        huanxinService.cancelDisturb(username);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("给用户发送文本消息")
    @PostMapping("/user/sendText")
    public AjaxResult sendText(@RequestBody SendMsgVO vo){
        String username = SecurityUtils.getUsername();
        huanxinService.sendTextToUser(username, vo.getTargetUsername(), vo.getMsg());
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("给用户发送图片消息")
    @PostMapping("/user/sendImg")
    public AjaxResult sendImg(@RequestBody SendImgVO vo){
        String username = SecurityUtils.getUsername();
        JSONObject imgVO = JSONObject.parseObject(JSONObject.toJSONString(vo.getImgVO()));
        huanxinService.sendMsgToUser(username, vo.getTargetUsername(),imgVO, MsgTypeEnum.IMG);

        return AjaxResult.success();
    }


    @SaCheckLogin
    @ApiOperation("给用户发送语音消息")
    @PostMapping("/user/sendAudio")
    public AjaxResult sendImg(@RequestBody SendAudioVO vo){
        String username = SecurityUtils.getUsername();
        JSONObject audioVo = JSONObject.parseObject(JSONObject.toJSONString(vo.getAudioVO()));
        huanxinService.sendMsgToUser(username, vo.getTargetUsername(),audioVo, MsgTypeEnum.IMG);
        return AjaxResult.success();
    }


    @SaCheckLogin
    @ApiOperation("发送视频消息")
    @PostMapping("/user/sendVideo")
    public AjaxResult sendVideo(@RequestBody SendVideoVO vo) {
        String username = SecurityUtils.getUsername();
        JSONObject videoVo = JSONObject.parseObject(JSONObject.toJSONString(vo.getVideoVO()));
        huanxinService.sendMsgToUser(username, vo.getTargetUsername(), videoVo, MsgTypeEnum.VIDEO);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("批量通过环信id获取直播信息")
    @PostMapping("/batchLiveUsersByUsernames")
    public AjaxResult<List<IMUserVO>> batchLiveUsersByUsernames(@RequestBody BatchLiveDTO dto){
        List<String> usernames = dto.getUsernames();

        List<User> users = userService.batchByUsernames(usernames);
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());

        List<PartyUser> partyUsers = partyUserService.getByUserIds(userIds);

        List<IMUserVO> imUserVOS = Lists.newLinkedList();
        for (User user : users) {
            IMUserVO userVO = new IMUserVO();
            userVO.setUsername(user.getUsername());
            userVO.setLiveStatus(UserLiveStatusEnum.NO_LIVE.getStatus());
            //处理用户语聊状态
            for (PartyUser partyUser : partyUsers) {
                if (user.getId().equals(partyUser.getUserId())) {
                    //再校验一次
                    ChannelUserVO vo = agoraClient.getUsers(partyUser.getPartyId()).toJavaObject(ChannelUserVO.class);
                    if (vo.getChannelExist()) {
                        List<String> broadcaseters = vo.getBroadcasters().stream().map(l -> l.toString()).collect(Collectors.toList());
                        List<String> audiences = vo.getAudience().stream().map(l -> l.toString()).collect(Collectors.toList());
                        LinkedList<String> allUsernames = Lists.newLinkedList();
                        allUsernames.addAll(broadcaseters);
                        allUsernames.addAll(audiences);
                        if (allUsernames.contains(user.getUsername())) {
                            userVO.setLiveStatus(UserLiveStatusEnum.VOICE_LIVE.getStatus());
                            userVO.setPartyId(partyUser.getPartyId());
                        }
                    }
                    break;
                }
            }
            imUserVOS.add(userVO);
        }



        return AjaxResult.success(imUserVOS);
    }



    @SaCheckLogin
    @ApiOperation("发送位置消息")
    @PostMapping("/user/sendLoc")
    private AjaxResult sendLoc(@RequestBody SendLocVO vo) {
        String username = SecurityUtils.getUsername();
        JSONObject videoVo = JSONObject.parseObject(JSONObject.toJSONString(vo.getLocVO()));
        huanxinService.sendMsgToUser(username, vo.getTargetUsername(), videoVo, MsgTypeEnum.LOC);
        return AjaxResult.success();
    }








}
